package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.AddressBean;
import com.project.mapper.IAddressMapper;
import com.project.service.IAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional
public class AddressServiceImpl implements IAddressService {

    @Autowired
    private IAddressMapper mapper;

    @Override
    public List<AddressBean> findByUserNum(Long userNum) {
        QueryWrapper<AddressBean> qw=new QueryWrapper<>();
        qw.eq("userNum",userNum);
        return mapper.selectList(qw);
    }

    @Override
    public void addAddress(AddressBean addressBean) {
        if (addressBean.getStatus()==0){//如果添加地址状态是默认地址
            this.SetStatus(addressBean.getUserNum());
            mapper.insert(addressBean);
        }else {//普通地址直接添加
            mapper.insert(addressBean);
        }

    }

    @Override
    public void addList(List<AddressBean> addressBeanList,Long userNum) {
        for (AddressBean a:addressBeanList) {
            a.setUserNum(userNum);
            mapper.insert(a);
        }
    }

    @Override
    public void updateAddress(AddressBean addressBean) {
        AddressBean address=mapper.selectById(addressBean.getAddressId());
        address.setStatus(addressBean.getStatus());
        address.setAddressInfo(addressBean.getAddressInfo());
        address.setArea(addressBean.getArea());
        address.setCity(addressBean.getCity());
        address.setProvince(addressBean.getProvince());
        address.setCneeName(addressBean.getCneeName());
        address.setCneePhone(addressBean.getCneePhone());
        address.setUserNum(addressBean.getUserNum());
        if (addressBean.getStatus()==0){//如果修改的地址是默认地址
            this.SetStatus(addressBean.getUserNum());
            mapper.updateById(address);
        }//普通地址就直接修改
        mapper.updateById(address);
    }

    @Override
    public void updateStatus(Long addressId) {
        AddressBean address=mapper.selectById(addressId);
        this.SetStatus(address.getUserNum());
        address.setStatus(0);
        mapper.updateById(address);
    }

    @Override
    public void del(Long addressId) {
        mapper.deleteById(addressId);
    }

    @Override
    public AddressBean findById(Long addressId) {
        return mapper.selectById(addressId);
    }

    //找出默认地址 并将它的默认状态改为普通状态
    public void SetStatus(Long userNum){
        QueryWrapper<AddressBean> qw=new QueryWrapper<>();
        qw.eq("status",0);
        qw.eq("userNum",userNum);
        AddressBean addressBean=mapper.selectOne(qw);
        if (addressBean==null){
            return;
        }
        addressBean.setStatus(1);
        mapper.updateById(addressBean);
    }
}
